package com.example.examsystem.controller;

import com.example.examsystem.dto.NoticeDto;
import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.service.NoticeService;
import com.example.examsystem.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 通知公告控制器
 * 处理通知的CRUD操作
 */
@RestController
@RequestMapping("/notices")
@RequiredArgsConstructor
@Slf4j
public class NoticeController {
    
    private final NoticeService noticeService;
    
    /**
     * 获取通知列表（管理员）
     * @param page 页码
     * @param size 每页大小
     * @param title 标题
     * @param type 类型
     * @param status 状态
     * @param targetType 目标类型
     * @param isTop 是否置顶
     * @param isUrgent 是否紧急
     * @param createdBy 创建者ID
     * @return 分页通知列表
     */
    @GetMapping("/admin")
    @PreAuthorize("hasAuthority('notice:view')")
    public ResponseEntity<PageResponse<NoticeDto>> getNotices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String targetType,
            @RequestParam(required = false) Boolean isTop,
            @RequestParam(required = false) Boolean isUrgent,
            @RequestParam(required = false) Long createdBy) {
        log.info("查询通知列表 - 页码: {}, 大小: {}, 筛选条件: 标题={}, 类型={}, 状态={}, 目标类型={}, 置顶={}, 紧急={}, 创建者={}", 
                page, size, title, type, status, targetType, isTop, isUrgent, createdBy);
        PageResponse<NoticeDto> notices = noticeService.getNotices(
            page, size, title, type, status, targetType, isTop, isUrgent, createdBy);
        return ResponseEntity.ok(notices);
    }
    
    /**
     * 获取用户可见的通知
     * @param page 页码
     * @param size 每页大小
     * @param type 类型
     * @return 分页通知列表
     */
    @GetMapping
    public ResponseEntity<PageResponse<NoticeDto>> getVisibleNotices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type) {
        log.info("获取用户可见通知 - 页码: {}, 大小: {}, 类型: {}", page, size, type);
        Long userId = SecurityUtils.getCurrentUserId();
        PageResponse<NoticeDto> notices = noticeService.getVisibleNotices(userId, page, size, type);
        return ResponseEntity.ok(notices);
    }
    
    /**
     * 获取通知详情
     * @param id 通知ID
     * @return 通知详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<NoticeDto> getNotice(@PathVariable Long id) {
        log.info("获取通知详情 - ID: {}", id);
        NoticeDto notice = noticeService.getNotice(id);
        return ResponseEntity.ok(notice);
    }
    
    /**
     * 创建通知
     * @param noticeDto 通知信息
     * @return 创建的通知
     */
    @PostMapping
    @PreAuthorize("hasAuthority('notice:create')")
    public ResponseEntity<NoticeDto> createNotice(@Valid @RequestBody NoticeDto noticeDto) {
        log.info("创建通知 - 标题: {}", noticeDto.getTitle());
        Long creatorId = SecurityUtils.getCurrentUserId();
        NoticeDto createdNotice = noticeService.createNotice(noticeDto, creatorId);
        return ResponseEntity.ok(createdNotice);
    }
    
    /**
     * 更新通知
     * @param id 通知ID
     * @param noticeDto 通知信息
     * @return 更新的通知
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('notice:edit')")
    public ResponseEntity<NoticeDto> updateNotice(@PathVariable Long id, 
                                                 @Valid @RequestBody NoticeDto noticeDto) {
        log.info("更新通知 - ID: {}", id);
        NoticeDto updatedNotice = noticeService.updateNotice(id, noticeDto);
        return ResponseEntity.ok(updatedNotice);
    }
    
    /**
     * 删除通知
     * @param id 通知ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('notice:delete')")
    public ResponseEntity<Map<String, String>> deleteNotice(@PathVariable Long id) {
        log.info("删除通知 - ID: {}", id);
        noticeService.deleteNotice(id);
        return ResponseEntity.ok(Map.of("message", "通知删除成功"));
    }
    
    /**
     * 发布通知
     * @param id 通知ID
     * @return 发布的通知
     */
    @PostMapping("/{id}/publish")
    @PreAuthorize("hasAuthority('notice:publish')")
    public ResponseEntity<NoticeDto> publishNotice(@PathVariable Long id) {
        log.info("发布通知 - ID: {}", id);
        NoticeDto publishedNotice = noticeService.publishNotice(id);
        return ResponseEntity.ok(publishedNotice);
    }
    
    /**
     * 归档通知
     * @param id 通知ID
     * @return 归档的通知
     */
    @PostMapping("/{id}/archive")
    @PreAuthorize("hasAuthority('notice:edit')")
    public ResponseEntity<NoticeDto> archiveNotice(@PathVariable Long id) {
        log.info("归档通知 - ID: {}", id);
        NoticeDto archivedNotice = noticeService.archiveNotice(id);
        return ResponseEntity.ok(archivedNotice);
    }
    
    /**
     * 批量操作通知
     * @param request 批量操作请求
     * @return 操作结果
     */
    @PostMapping("/batch")
    @PreAuthorize("hasAuthority('notice:edit')")
    public ResponseEntity<Map<String, Object>> batchOperateNotices(@RequestBody Map<String, Object> request) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) request.get("ids");
        String action = (String) request.get("action");
        
        log.info("批量操作通知 - 操作: {}, 数量: {}", action, ids.size());
        int count = noticeService.batchOperateNotices(ids, action);
        return ResponseEntity.ok(Map.of("operatedCount", count, "message", "批量操作成功"));
    }
    
    /**
     * 获取置顶通知
     * @return 置顶通知列表
     */
    @GetMapping("/top")
    public ResponseEntity<List<NoticeDto>> getTopNotices() {
        log.info("获取置顶通知");
        List<NoticeDto> topNotices = noticeService.getTopNotices();
        return ResponseEntity.ok(topNotices);
    }
    
    /**
     * 获取紧急通知
     * @return 紧急通知列表
     */
    @GetMapping("/urgent")
    public ResponseEntity<List<NoticeDto>> getUrgentNotices() {
        log.info("获取紧急通知");
        List<NoticeDto> urgentNotices = noticeService.getUrgentNotices();
        return ResponseEntity.ok(urgentNotices);
    }
}